package arithmetic.LeetCode;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author jiangfeng on 2023/6/3
 */
public class EatenApples {
    public static void main(String[] args) {
        System.out.println(new Solution().eatenApples(new int[]{1,2,3,5,2},new int[]{3,2,1,4,2}));
        System.out.println(new Solution().eatenApples(new int[]{3,0,0,0,0,2},new int[]{3,0,0,0,0,2}));
    }

    static class Solution {
        public int eatenApples(int[] apples, int[] days) {
            // 使用优先队列
            int curDay = 1;
            // 结束时间放入优先队列.
            PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt((int[] e) -> e[0]));
            int i = 0;
            int res =0;
            while( !q.isEmpty() || i < apples.length ){
                if(i<apples.length){
                    q.offer(new int[]{curDay+days[i]-1,apples[i]});
                    i++;
                }
                while (!q.isEmpty() && q.peek()[0]<curDay){
                    q.poll();
                }
                if(!q.isEmpty() ){
                    int[] e = q.peek();
                    if(e[0]>=curDay){
                        res++;
                        e[1]--;
                    }
                    if(e[1]<=0) {
                        q.poll();
                    }
                }
                curDay++;
            }
            return res;

        }
    }
}
